package com.linkstec.util;

import java.sql.Blob;
import java.sql.Clob;
import java.sql.SQLException;

import org.apache.commons.beanutils.ConvertUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * 字段类型转换
 * @author linkage
 *
 */
public class ConvertUtil {
	private static final Logger logger = LogManager.getLogger();

	/**
	 * 支持的转换类型
	 * java.lang.BigDecimal 
	 * java.lang.BigInteger 
	 * boolean and java.lang.Boolean
	 * byte and java.lang.Byte 
	 * char and java.lang.Character 
	 * java.lang.Class
	 * double and java.lang.Double 
	 * float and java.lang.Float 
	 * int and java.lang.Integer 
	 * long and java.lang.Long 
	 * short and java.lang.Short
	 * java.lang.String 
	 * java.sql.Date 
	 * java.sql.Time 
	 * java.sql.Timestamp
	 * 
	 * @param value
	 * @param type
	 * @return
	 */
//	public static Object convert(Object value, Class<?> type)
//	{
//		if(value == null){
//			return null;
//		}
//		
//		Converter converter = CONVERT_UTILS_BEAN.lookup(type);
//		if (converter != null) {
//			LLog.debug("        USING CONVERTER " + converter);
//			return converter.convert(type, value);
//		}
//		LLog.warn("没有找到该类型(" + type.getName() + ")转换器,返回原值：" + value==null? null:value.toString());
//		return value;
//	}
	@SuppressWarnings("unchecked")
	public static <T> T convert(Object value, Class<T> type)
	{
		if(value == null){
			return  null;
		}
		if(value instanceof Clob){
			return (T)convertFromClob((Clob)value);
		}
		
		if(value instanceof Blob){
			return (T)convertFromBlob((Blob)value);
		}
		return (T)ConvertUtils.convert(value, type);
	}
	
	public static Object convertToObject(Object value, Class<?> type)
	{
		if(value == null){
			return  null;
		}
		
		if(value instanceof Clob){
			return convertFromClob((Clob)value);
		}else if(value instanceof Blob){
			return convertFromBlob((Blob)value);
		}else if(type.toString().equals(value.getClass().toString())){
			return value;
		}
		
		return ConvertUtils.convert(value, type);
	}
	
	public static byte[] convertFromBlob(Blob blob){
		if (null != blob) {
	    	try {
				return blob.getBytes(1, (int) blob.length());
			} catch (SQLException e) {
				logger.info("Blob类型转换出错");
				return  null;
			}
	    }
		
		return  null;
		
	}
	
	public static String convertFromClob(Clob clob){
		if (null != clob) {
			int size;
			try {
				size = (int) clob.length();
				return clob.getSubString(1, size);
			} catch (SQLException e) {
				logger.info("Clob类型转换出错");
				return  null;
			}
	    }
		
		return  null;
		
	}
}
